package com.lin.filegraph.utils.analyze;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @description:
 * @author: linhuaixu
 * @time: 2023/5/18 15:54
 */

public class ExcelPoi {
    public String projectPath;
    public List<String[]> comList;
    public String language;

    public ExcelPoi(String fileName) {
        comList = new ArrayList<String[]>();
        projectPath = null;
        language = null;
        analyze(fileName);
    }
    private List<String[]> analyze(String fileName) {

        boolean isFind = false;
        try {
            Workbook wb = checkFile(fileName);
            // 遍历所有sheet
            System.out.println("表格总数:" + wb.getNumberOfSheets());
            for (int i = 0; i < wb.getNumberOfSheets(); i++) {
                // 只解析一张不空的表
                if (!isFind) {
                    Sheet sheet = wb.getSheetAt(i);
                    System.out.println("****分析表格:" + sheet.getSheetName() + "*****");
                    if (sheet.equals(null)) {
                        continue;
                    }
                    // 获得当前sheet的开始行
                    int firstRowNum = sheet.getFirstRowNum();

                    // 检查是否符合格式
                    boolean isStandard = checkStandard(sheet, firstRowNum);

                    // 遍历组件输入
                    if (isStandard) {
                        // System.out.println("开始遍历....");
                        // 获得当前sheet的结束行
                        int lastRowNum = sheet.getLastRowNum();
                        // 循环除了前四行的所有行
                        for (int rowNum = firstRowNum + 3; rowNum <= lastRowNum; rowNum++) {
                            // 获得当前行
                            Row row = sheet.getRow(rowNum);
                            if (row == null) {
                                continue;
                            }
                            // 获得当前行的开始列
                            int firstCellNum = row.getFirstCellNum();
                            // 获得当前行的列数
                            int lastCellNum = row.getPhysicalNumberOfCells();
                            if(row.getCell(2) == null)
                                continue;
                            //再次判断合格性
                            if (lastCellNum < 3 || firstCellNum != 0 || row.getCell(2) == null || row.getCell(0) == null) {
                                isStandard = false;
                                break;
                            }

                            String[] cells = new String[4];
                            // 循环当前行
                            for (int cellNum = firstCellNum; cellNum < 4; cellNum++) {
                                Cell cell = row.getCell(cellNum);
//								System.out.println(getCellValue(cell));
                                String str = getCellValue(cell);
                                cells[cellNum] = str;
                            }
                            comList.add(cells);
                        }
                        // 标记找到了
                        if (isStandard) {
                            isFind = true;
                        }
                    }
                    // 不合格报错
                    if (!isStandard) {
                        System.out.println("表格——" + sheet.getSheetName() + "已经被修改或者填写格式不符合！");
                        System.out.println("***************");
                        continue;
                    }
                    System.out.println("***************");
                }
            }
            //wb.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (isFind) {
            System.out.println("架构excel恢复完毕！！！");
            return comList;
        } else {
            System.out.println("没找到符合条件的组件输入！！！");
            return null;
        }
    }

    // 判断表格是否合格
    private boolean checkStandard(Sheet sheet, int firstRowNum) {
        boolean isStandard = false;
        Cell ce1 = sheet.getRow(firstRowNum + 0).getCell(0);
        Row row2 = sheet.getRow(firstRowNum + 1);
        Cell ce3 = sheet.getRow(firstRowNum + 2).getCell(0);
        if (ce1 != null && getCellValue(ce1).equals("注：请不要改动格式！（详情见第二张表格）")) {
            // 判断项目路径
            if (row2.getCell(1) != null && getCellValue(row2.getCell(0)).equals("项目名")) {
                if (getCellValue(row2.getCell(1)) != null) {
                    projectPath = getCellValue(row2.getCell(1));
                    System.out.println("项目名" + projectPath);
                    // 判断编程语言
                    if (row2.getCell(3) != null && getCellValue(row2.getCell(2)).equals("编程语言")) {
                        language = getCellValue(row2.getCell(3));
                        System.out.println("编程语言" + language);
                        if (ce3 != null && getCellValue(ce3).equals("实体")) {
                            isStandard = true;
                        }
                    }

                }

            }
        }
        return isStandard;
    }

    private Workbook checkFile(String fileName) {
        Workbook wb = null;
        try {
            InputStream inputExcel = new FileInputStream(fileName);
            if (fileName.endsWith(".xls")) {
                wb = new HSSFWorkbook(inputExcel);
            } else if (fileName.endsWith(".xlsx")) {
//                wb = new XSSFWorkbook(inputExcel);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件不存在！");
        } catch (IOException e) {
            e.printStackTrace();
        }
        return wb;
    }

    private String getCellValue(Cell cell) {
        String cellValue = "";
        if (cell == null) {
            return null;
        }
//         把数字当成String来读，避免出现1读成1.0的情况
        if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
            cell.setCellType(Cell.CELL_TYPE_STRING);
        }
//         判断数据的类型
        switch (cell.getCellType()) {
            case Cell.CELL_TYPE_NUMERIC: // 数字
                cellValue = String.valueOf(cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING: // 字符串
                cellValue = String.valueOf(cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_BOOLEAN: // Boolean
                cellValue = String.valueOf(cell.getBooleanCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA: // 公式
                cellValue = String.valueOf(cell.getCellFormula());
                break;
            case Cell.CELL_TYPE_BLANK: // 空值
                cellValue = "";
                break;
            case Cell.CELL_TYPE_ERROR: // 故障
                cellValue = "非法字符";
                break;
            default:
                cellValue = "未知类型";
                break;
        }
         System.out.println("分析的单元格："+cellValue);
        return cellValue;
    }

}

